﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Logging;

namespace Dukou.Search
{
    /// <summary>
    /// 搜索服务
    /// </summary>
    public class SearchService : SearchContextFactory, ISearchService
    {
        /// <summary>
        /// 日志记录器
        /// </summary>
        private static readonly ILog log = LogManager.GetLogger(typeof(SearchService));

        /// <summary>
        /// 获取 / 设置 搜索器工厂集合
        /// </summary>
        public IList<ISearcherFactory> SearcherFactories { get; set; }

        #region ISearchService 成员

        /// <summary>
        /// 进行搜索
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public ISearchResult Search(ISearchContext context)
        {
            //Check.Require(context != null);

            // 检查缓存结果
            if (this.SearcherFactories == null || this.SearcherFactories.Count == 0)
            {
                return null;
            }

            // 遍历搜索器工厂，寻找可用的搜索器
            foreach (ISearcherFactory factory in this.SearcherFactories)
            {
                ISearcher searcher = factory.CreateSearcher(context.ContentType);
                if (searcher != null)
                {
                    try
                    {
                        return searcher.Search(context);
                    }
                    catch (Exception ex)
                    {
                        log.Error(string.Format("搜索 {0} 时失败", context.ContentType), ex);
                        return null;
                    }
                }
            }

            return null;
        }

        #endregion
    }
}
